import { AvatarDropdown, AvatarName, Footer, Question } from '@/components';
import { getMenu, currentUser as queryCurrentUser } from '@/services/ant-design-pro/api';
import * as iconMap from '@ant-design/icons';
import { Settings as LayoutSettings, SettingDrawer } from '@ant-design/pro-components';
import { Link, RunTimeLayoutConfig, history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import fixMenuItemIcon from './utils/menu';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  userRoutes?: API.MenuRouteItem[];
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser({
        skipErrorHandler: true,
      });
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    const userRoutes: any[] = [];
    return {
      fetchUserInfo,
      currentUser,
      userRoutes,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    userRoutes: [],
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

function processRoutes(routes: API.MenuRouteItem[]) {
  if (!routes) {
    return;
  }
  routes.forEach((route) => {
    if (route.routes) {
      processRoutes(route.routes);
      if (!route.routes.length) {
        route.hideInMenu = true;
      }
    }
  });
  return routes;
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    // iconfont 地址
    menu: {
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: {
        userid: initialState?.currentUser?.userid,
      },
      request: async (params) => {
        if (params.userid) {
          const { data } = await getMenu();
          const menuData = processRoutes(data?.list || []);
          const fixMenuData = fixMenuItemIcon(menuData || []);
          setInitialState({ ...initialState, userRoutes: fixMenuData });
          return fixMenuData;
        }
        return [];
      },
    },
    iconfontUrl: initialState?.settings?.iconfontUrl,
    actionsRender: () => [<Question key="doc" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: isDev
      ? [
          <a
            href="https://mortise-and-tenon.gitee.io/mortnon-docs/#/"
            target="_blank"
            rel="noreferrer noopener"
            key="homepage"
          >
            <iconMap.HomeOutlined />
            <span>卯榫官网</span>
          </a>,
          <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
            <iconMap.LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 二级目录
    subMenuItemRender: (menuItemProps, defaultDom) => {
      if (menuItemProps.isUrl || !menuItemProps.path) {
        return defaultDom;
      }

      let shouldRenderIcon =
        menuItemProps.pro_layout_parentKeys && menuItemProps.pro_layout_parentKeys.length > 0;

      const splitMenus = initialState?.settings?.splitMenus;

      const siderMenuType = initialState?.settings?.siderMenuType;
      // 如果开启了自动拆分菜单，二级菜单会变成一级菜单，消除
      if (splitMenus || siderMenuType === 'group') {
        shouldRenderIcon = menuItemProps.pro_layout_parentKeys.length > 1 || false;
      }

      // 如果开启自动拆分菜单和分组模式，超过二级菜单也会变成一级菜单
      if (splitMenus && siderMenuType === 'group') {
        shouldRenderIcon = false;
      }
      return (
        <span>
          {shouldRenderIcon ? (
            <span style={{ display: 'flex', alignItems: 'center' }}>
              {menuItemProps.icon}
              <span style={{ marginLeft: '8px' }}>{defaultDom}</span>
            </span>
          ) : (
            defaultDom
          )}
        </span>
      );
    },
    // 二级菜单
    menuItemRender: (menuItemProps, defaultDom) => {
      if (menuItemProps.isUrl || !menuItemProps.path) {
        return defaultDom;
      }

      // debugger
      let shouldRenderIcon =
        menuItemProps.pro_layout_parentKeys && menuItemProps.pro_layout_parentKeys.length > 0;

      const splitMenus = initialState?.settings?.splitMenus;
      const siderMenuType = initialState?.settings?.siderMenuType;
      // 如果开启了自动拆分菜单，二级菜单会变成一级菜单，消除重复icon
      if (splitMenus || siderMenuType === 'group') {
        shouldRenderIcon = menuItemProps.pro_layout_parentKeys.length > 1 || false;
      }

      // 如果开启自动拆分菜单和分组模式，超过二级菜单也会变成一级菜单
      if (splitMenus && siderMenuType === 'group') {
        shouldRenderIcon = false;
      }

      return (
        <Link to={menuItemProps.path}>
          {shouldRenderIcon ? (
            <span style={{ display: 'flex', alignItems: 'center' }}>
              {menuItemProps.icon}
              <span style={{ marginLeft: '8px' }}>{defaultDom}</span>
            </span>
          ) : (
            defaultDom
          )}
        </Link>
      );
    },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
